// +----------------------------------------------------------------------
// | JavaWeb_EleVue_Pro前后端分离旗舰版框架 [ JavaWeb ]
// +----------------------------------------------------------------------
// | 版权所有 2021 上海JavaWeb研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.javaweb.vip/
// +----------------------------------------------------------------------
// | 作者: 鲲鹏 <javaweb520@gmail.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

package com.javaweb.admin.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javaweb.admin.config.SendEmailConfig;
import com.javaweb.admin.config.SendEmailJob;
import com.javaweb.admin.entity.filenameRule.RuleInvoiceno;
import com.javaweb.admin.entity.filenameRule.SaleinvoiceDownload;
import com.javaweb.admin.mapper.SaleInvoiceMapper;
import com.javaweb.admin.mapper.SaleinvoiceDownloadMapper;
import com.javaweb.admin.vo.invoicefilenamerule.InvoiceFilenameRuleAddVo;
import com.javaweb.common.utils.*;
import com.javaweb.common.common.BaseQuery;
import com.javaweb.common.common.BaseServiceImpl;
import com.javaweb.admin.entity.InvoiceFilenameRule;
import com.javaweb.admin.mapper.InvoiceFilenameRuleMapper;
import com.javaweb.admin.query.InvoiceFilenameRuleQuery;
import com.javaweb.admin.service.IInvoiceFilenameRuleService;
import com.javaweb.system.utils.ShiroUtils;
import com.javaweb.admin.vo.invoicefilenamerule.InvoiceFilenameRuleInfoVo;
import com.javaweb.admin.vo.invoicefilenamerule.InvoiceFilenameRuleListVo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;

/**
 * <p>
 * 服务类实现
 * </p>
 *
 * @author 鲲鹏
 * @since 2024-07-31
 */
@Service
public class InvoiceFilenameRuleServiceImpl extends BaseServiceImpl<InvoiceFilenameRuleMapper, InvoiceFilenameRule> implements IInvoiceFilenameRuleService {

    @Autowired
    private InvoiceFilenameRuleMapper invoiceFilenameRuleMapper;
    @Autowired
    private SaleInvoiceMapper saleInvoiceMapper;
    @Autowired
    private SaleinvoiceDownloadMapper saleinvoiceDownloadMapper;
    @Autowired
    private SendEmailConfig sendEmailConfig;
    /**
     * 获取数据列表
     *
     * @param query 查询条件
     * @return
     */
    @Override
    public JsonResult getList(BaseQuery query) {
        InvoiceFilenameRuleQuery invoiceFilenameRuleQuery = (InvoiceFilenameRuleQuery) query;
        // 查询条件
        QueryWrapper<InvoiceFilenameRule> queryWrapper = new QueryWrapper<>();
        // queryWrapper.orderByDesc("id");

        // 获取数据列表
        IPage<InvoiceFilenameRule> page = new Page<>(invoiceFilenameRuleQuery.getPage(), invoiceFilenameRuleQuery.getLimit());
        IPage<InvoiceFilenameRule> pageData = invoiceFilenameRuleMapper.selectPage(page, queryWrapper);
        pageData.convert(x -> {
            InvoiceFilenameRuleListVo invoiceFilenameRuleListVo = Convert.convert(InvoiceFilenameRuleListVo.class, x);
            return invoiceFilenameRuleListVo;
        });
        return JsonResult.success(pageData);
    }

    /**
     * 获取详情Vo
     *
     * @param id 记录ID
     * @return
     */
    @Override
    public Object getInfo(Serializable id) {
        InvoiceFilenameRule entity = (InvoiceFilenameRule) super.getInfo(id);
        // 返回视图Vo
        InvoiceFilenameRuleInfoVo invoiceFilenameRuleInfoVo = new InvoiceFilenameRuleInfoVo();
        // 拷贝属性
        BeanUtils.copyProperties(entity, invoiceFilenameRuleInfoVo);
        return invoiceFilenameRuleInfoVo;
    }

    /**
     * 添加、更新记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult edit(InvoiceFilenameRule entity) {
        if (StringUtils.isNotNull(entity.getId()) && entity.getId() > 0) {
            entity.setUpdateTime(DateUtils.now());
            entity.setUpdateUser(ShiroUtils.getUserId());
        } else {
            entity.setCreateTime(DateUtils.now());
            entity.setCreateUser(ShiroUtils.getUserId());
        }
        return super.edit(entity);
    }

    /**
     * 删除记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult delete(InvoiceFilenameRule entity) {
        entity.setUpdateTime(DateUtils.now());
        entity.setUpdateUser(1);
        entity.setMark(0);
        return super.delete(entity);
    }

    @Override
    public JsonResult add(InvoiceFilenameRuleAddVo vo) {
        String pdfrules = "";
        String ziprules = "";
        for (int i = 0; i < vo.getZipruleField().length; i++) {
            if (i == 0) {
                ziprules += vo.getZipruleField()[i];
            } else {
                ziprules += "," + vo.getZipruleField()[i];
            }
        }
        for (int i = 0; i < vo.getPdfruleField().length; i++) {
            if (i == 0) {
                pdfrules += vo.getPdfruleField()[i];
            } else {
                pdfrules += "," + vo.getPdfruleField()[i];
            }
        }
        vo.setZiprules(ziprules);
        vo.setPdfrules(pdfrules);
        invoiceFilenameRuleMapper.add(vo);
        return JsonResult.success();
    }

    @Override
    public JsonResult getInvoiceRuleList(BaseQuery query) {
        InvoiceFilenameRuleQuery invoiceFilenameRuleQuery = (InvoiceFilenameRuleQuery) query;
        IPage<InvoiceFilenameRule> page = new Page<>(invoiceFilenameRuleQuery.getPage(), invoiceFilenameRuleQuery.getLimit());
        IPage<InvoiceFilenameRule> pageData = invoiceFilenameRuleMapper.getInvoiceRuleList(page, invoiceFilenameRuleQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult edit(InvoiceFilenameRuleAddVo vo) {

        invoiceFilenameRuleMapper.deleteById(vo.getId());
        this.add(vo);
        sendEmailConfig.configureTasks(new ScheduledTaskRegistrar());
        return JsonResult.success();
    }

    @Override
    public JsonResult deleteById(Integer id) {
        invoiceFilenameRuleMapper.deleteById(id);
        return JsonResult.success();
    }

    @Override
    public JsonResult updateFile(String customerCode) {
        //FileUploadAndDownloadUtil.UserLogin();
        {
            InvoiceFilenameRuleQuery invoiceFilenameRuleQuery = new InvoiceFilenameRuleQuery();
            invoiceFilenameRuleQuery.setCustomerCode(customerCode);
            invoiceFilenameRuleQuery.setPage(1);
            invoiceFilenameRuleQuery.setLimit(10);
            IPage<InvoiceFilenameRule> page = new Page<>(invoiceFilenameRuleQuery.getPage(), invoiceFilenameRuleQuery.getLimit());
            IPage<InvoiceFilenameRule> pageData = invoiceFilenameRuleMapper.getInvoiceRuleList(page, invoiceFilenameRuleQuery);
            if (!pageData.getRecords().isEmpty()) {

                String Path = "D:\\home\\invoice";

                File dir = new File(Path);
                List<File> allFileList = new ArrayList<>();
                if (!dir.exists()) {
                    System.out.println("目录不存在");
                    return JsonResult.error("目录不存在");
                }
                File[] fileList = dir.listFiles();

                String allpdfRule = "";
                String allzipRule = "";

                List<RuleInvoiceno> ruleInvoicenoList = new ArrayList<>();
                String custName = invoiceFilenameRuleQuery.getCustomerCode();
                /*获取规则*/

                InvoiceFilenameRule invoiceFilenameRule = pageData.getRecords().get(0);
                //获取pdf命名规则
                String pdfrules = invoiceFilenameRule.getPdfruleField();
                //获取zip命名规则
                String ziprules = invoiceFilenameRule.getZipruleField();


                String[] pdfrule, ziprule;
                //根据逗号拆分
                pdfrule = pdfrules.split(",");
                ziprule = ziprules.split(",");

                List<SaleinvoiceDownload> saleinvoiceDownload = saleinvoiceDownloadMapper.getSaleinvoiceDownload(customerCode);

                for (SaleinvoiceDownload sd : saleinvoiceDownload) {
                    for (String str : pdfrule) {
                        if (str.equals("发票号")) {
                            allpdfRule += sd.getVbillcode() + "_";
                        }
                        if (str.equals("开票日期")) {
                            allpdfRule += sd.getDbilldate() + "_";
                        }
                        if (str.equals("摘要") && !sd.getVnote().isEmpty()) {
                            allpdfRule += sd.getVnote() + "_";
                        }
                        if (str.equals("金额")) {
                            allpdfRule += sd.getNtotalorigmny() + "_";
                        }

                    }


                    //找到发票号对应的文件,并改名
                    if (fileList != null && !pdfrules.isEmpty()) {
                        for (File file : fileList) {
                            if (file.isFile() && file.getName().equals(sd.getPdffilename())) {
                                /*重命名文件*/
                                file.renameTo(new File(Path + "\\" + allpdfRule + "." + FilenameUtils.getExtension(file.getName())));
                                break;

                            }
                        }
                    }
                    allpdfRule = "";

                }



                /*获取规则字段*/


                fileList = dir.listFiles();


                /*获取文件夹中所有文件*/
                if (fileList != null) {
                    for (File file : fileList) {
                        if (file.isFile()) {
                            allFileList.add(file);
                        }
                    }
                }
                /*zip文件命名*/
                for (String str : ziprule) {
                    if (str.equals("公司名")) {
                        allzipRule += invoiceFilenameRule.getCustomerName() + '_';

                    }

                    if (str.equals("开票日期")) {
                        allzipRule += DateUtils.getDate() + '_';
                    }

                    if (str.equals("默认")) {
                        allzipRule += DateUtils.getDate() + '_';
                    }
                }

                /*打包压缩*/
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(Path + "\\" + allzipRule + ".zip");
                    ZipUtils.zip(allFileList, fileOutputStream);
                    fileOutputStream.close();
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }


                /*发送邮箱*/
            MailUtils.SendAttachMail("125029854@qq.com", "nqdzgnvmhcpgbjjh"
                    , "qq", "测试", "测试内容..........",
                    "125029854@qq.com", "dapan163@163.com", Path + "\\" + allzipRule + ".zip", allzipRule);

            }
        }
        return JsonResult.success();
    }


}